<!-- 用户 》 组织 -->

<template>
  <FormSlot
    class="UserList-UserOrgan"
    :bind="`${bindKey}Str`"
    :tip="`请选择${CORE.MAP.ORGAN}`"
    noLabel
    noMargin
    required
  >
    <div class="row9">
      <FormSwitch bind="organCheckAll" text="全选" isCheckbox eighth @change="changeAll" />
      <FormSwitch bind="organCheckLink" text="级联选择" isCheckbox sixth @change="changeLink" />

      <EasyScroll class="el-input__inner">
        <el-tree ref="tree" v-bind="treeProps" @check="changeOrgan" />
      </EasyScroll>
    </div>
  </FormSlot>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import MyRegion from '@admin/views/System/User/UserRole/MyModal/MyRegion'

// ============================== 导出组件 ============================== //

export default CORE.extend(MyRegion, {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'UserOrgan',

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    ...MyRegion.computed,

    /**
     * 绑定键
     */
    bindKey: () => 'organId',

    /**
     * 结构树数据
     */
    treeData: () => CORE.ORGAN.TREE,

    /**
     * 所有 ID 的列表
     */
    allIdList() {
      const idList = []
      const setIds = (children = []) => children.forEach((organ) => {
        idList.push(organ.id)
        setIds(organ.children)
      })
      setIds(this.treeData)
      return idList
    },

    /**
     * 结构树属性
     */
    treeProps() {
      const { treeData, one: { organCheckAll, organCheckLink } } = this
      return {
        key: `${organCheckAll}-${organCheckLink}`,
        data: treeData,
        nodeKey: 'id',
        props: { children: 'children', label: 'name' },
        indent: 32,
        showCheckbox: true,
        checkStrictly: organCheckLink !== 1,
        defaultExpandAll: true,
      }
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 初始化
     */
    init() {
      const { $refs, one: { organId } } = this
      $refs.tree.setCheckedKeys(organId)
    },

    /**
     * 切换组织
     */
    changeOrgan(node, { checkedKeys }) {
      const { one, bindKey, allIdList } = this
      one[bindKey] = checkedKeys
      one[`${bindKey}Str`] = one[bindKey].join()
      one.organCheckAll = one[bindKey].length === allIdList.length ? 1 : 2
    },

    /**
     * 切换全选
     */
    async changeAll(value) {
      await this.$nextTick()
      const { one, bindKey, allIdList } = this
      one[bindKey] = value === 1 ? [...allIdList] : []
      one[`${bindKey}Str`] = one[bindKey].join()
      this.init()
    },

    /**
     * 切换级联
     */
    async changeLink() {
      await this.$nextTick()
      this.init()
    },
  },
})
</script>

<style lang="scss">
@import './index.scss';
</style>
